A good answer might be:

  1. The initial values must be set up correctly.
  2. The condition in the while loop must be correct.
  3. The change in variable(s) must be done correctly.

Counting Upwards by Two's

If you change one of these three parts, the loop will do something different. Here is a section of a Java program that counts upwards by two's:

int count = 0;            // count is initialized
while ( count <= 6 )      // count is tested
{
  System.out.println( "count is:" + count );
  count = count + 2;      // count is increased by 2
}
System.out.println( "Done counting by two's." );      

Here is what the program prints:

count is: 0
count is: 2
count is: 4
count is: 6
Done counting by two's.

Here is what happens, step-by-tedious-step:

  1. count is initialized to 0.

  2. The condition, count <= 6 is evaluated, yielding TRUE.
  3. The loop body is executed, printing "count is: 0" and adding 2 to count.

  4. The condition, count <= 6 is evaluated, yielding TRUE
  5. .
  6. The loop body is executed, printing "count is: 2" and adding 2 to count.

  7. The condition, count <= 6 is evaluated, yielding TRUE.
  8. The loop body is executed, printing "count is: 4" and adding 2 to count.

  9. The condition, count <= 6 is evaluated, yielding TRUE.
  10. The loop body is executed, printing "count is: 6" and adding 2 to count.

  11. The condition, count <= 6 is evaluated, yielding FALSE.
  12. The body of the loop is skipped and the statement after the body is executed.

QUESTION 2:

Let us make just one change to the program fragment: we will change the initialization of count to:

int count = 1; 

What does the program print out? (This is a slightly tricky question. Please take time to work out the answer.)